package com.strawcom.charmring.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import com.strawcom.charmring.R;
import com.strawcom.charmring.util.BaseUtil;

public class ProgressLineView extends View {
	private Paint paint = new Paint();
	private int mWidth;
	private int mHeight;
	private int progress;
	private int progressPadding;

	private int lineWidth;
	private int progressTextSize;
	private int progressColor;
	private int completedColor;
	private int waitingColor;

	public ProgressLineView(Context context) {
		this(context, null);
	}

	public ProgressLineView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public ProgressLineView(Context context, AttributeSet attrs,
			int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		progressPadding = 5;

		lineWidth = BaseUtil.dip2px(context, 1);
		progressTextSize = BaseUtil.sp2px(context, 12);
		progressColor = 0xff515151;
		completedColor = 0xff085cb2;
		waitingColor = 0xffa7f0f9;

		paint.setStrokeWidth(lineWidth);
		paint.setTextSize(progressTextSize);
	}

	public void updateProgress(int progress) {
		this.progress = progress;
		invalidate();
	}
	
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);
		mWidth = w;
		mHeight = h;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		final String progressInfo = progress + "%";
		float[] textWidths = new float[progressInfo.length()];
		paint.getTextWidths(progressInfo, textWidths);
		float textTotalWidth = calcTotal(textWidths);
		float cellWidth = (mWidth - (textTotalWidth + progressPadding * 2)) / 100;

		paint.setColor(completedColor);
		canvas.drawLine(0f, mHeight / 2f, cellWidth * progress, mHeight / 2f,
				paint);
		paint.setColor(progressColor);
		canvas.drawText(progressInfo, cellWidth * progress + progressPadding,
				(mHeight + progressTextSize) / 2, paint);
		paint.setColor(waitingColor);
		canvas.drawLine(mWidth - cellWidth * (100 - progress), mHeight / 2f,
				mWidth, mHeight / 2f, paint);
	}

	private float calcTotal(float[] arrFloat) {
		float result = 0f;
		for (float f : arrFloat) {
			result += f;
		}
		return result;
	}
}
